package com.example.config;


import io.minio.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * Minio工具类
 */
@Data
@Slf4j
@AllArgsConstructor
public class MinioTemplate {

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @SneakyThrows
    public String upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            // 生成UUID文件名
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpoint())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }

            setPolicy(minioClient);

            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .build());
            //文件访问路径
            String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
            return url;
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return "";
    }

    @SneakyThrows
    private void setPolicy(MinioClient minioClient) {
        // Define the policy string
        String policy = "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"s3:GetObject\"\n" +
                "            ],\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "    \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + minioProperties.getBucketName() + "/*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        // Set the bucket policy
        minioClient.setBucketPolicy(
                SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(policy)
                        .build());

    }

}
